package com.ww.springboot.boot.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.ww.springboot.boot.config.RedisUtils;
import com.ww.springboot.boot.redisson.RedisLock;
import com.ww.springboot.boot.service.IRedisService2;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 描述：
 *
 * @author wanwei
 * @since 2021-08-02 16:57
 */
@Service
@AllArgsConstructor
public class IRedisService2Impl implements IRedisService2 {

    private final RedisUtils redisUtils;

    @RedisLock(value = "redis:plus:secKill:lock", param = "#name")
    @Override
    public String getFromDataSource(String name) {
        redisUtils.incr(RedisServiceImpl.secKill + "total");
        try {
            String str = redisUtils.get(RedisServiceImpl.secKill + name);
            if (ObjectUtil.isNotEmpty(str)) {
                return str;
            }
            System.out.println(Thread.currentThread().getName() + "    -----     " + name);
            //从数据库拿数据 占用更多时间
            TimeUnit.MILLISECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String result = RedisServiceImpl.map.get(name);
        if (ObjectUtil.isNotEmpty(result)) {
            redisUtils.set(RedisServiceImpl.secKill + name, result);
        } else {
            redisUtils.set(RedisServiceImpl.secKill + name, "null");
        }
        return result;
    }
}
